from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from .models import *
import sys
sys.path.append('..')
from user.models import *
# Create your views here.

#用户上传页面
def Upload(request,user):
    user_id = UserId.objects.get(user_account = user).id
    user_name = UserId.objects.get(pk = user_id)
    context = {'user_name':user_name.user_account,'user_id':user_id}
    return render(request,'upload/upload.html',context)

#用户添加贴吧传入数据库
def Introduction(request,user):
    user_id = UserId.objects.get(user_account = user).id
    #调用函数
    shangchuan(request,user_id,img = 'postimg')
    postset = dict(request.POST)
    print(postset)
    
    user = UserId.objects.get(pk = user_id)
    post = user.post_set.create(post_name = postset['title'],post_info = postset['info'],)
    return render(request,'upload/index.html',context)

#上传贴吧图片
def shangchuan(request,user_id,img = None):
    request.session['user']
    #session字典报错
    if request.method == "POST":    # 请求方法为POST时，进行处理  
        myFile =request.FILES.get("excel", None)    # 获取上传的文件，如果没有文件，则默认为None  
        if not myFile:  
            return HttpResponse("没有文件上传!")
        user = UserId.objects.get(pk = user_id).user_account
        destination = open(os.path.join(r"media/",img,user,r'/.jpg'),'ab+')    # 打开特定的文件进行二进制的写操作  
        for chunk in myFile.chunks():      # 分块写入文件  
            destination.write(chunk)  
        destination.close()  
        return HttpResponse('ok')


    















    
